package com.sam.kafka.transaction;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: wm.xue
 * @date: 2021/11/12 18:29
 * @description: 发送消息 - 使用事务保证消息的仅一次发送
 */
public class _01_Producer_Transaction {
    public static void main(String[] args) {

        Map<String, Object> configs = new HashMap<>();
        configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.100.17.117:9092");
        configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        // 要求ISR都确认
        configs.put(ProducerConfig.ACKS_CONFIG, "all");
        // 提供的客户端ID
        configs.put(ProducerConfig.CLIENT_ID_CONFIG, "_01_Producer_Transaction");


        // 事务ID
        configs.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "_01_Producer_Transaction");
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(configs);
        // 初始化事务
        producer.initTransactions();
        // 开启事务
        producer.beginTransaction();


        try {
            producer.send(new ProducerRecord<>("tp_tx_01", "第3次事务消息"));
            int i = 1/0;

            // 提交事务
            producer.commitTransaction();
        } catch (Exception e) {
            // 回滚事务
            producer.abortTransaction();

        }

    }
}
